package util;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetTweetsURL {
	private static FileOutputStream tweets;
	private static BufferedReader usuarios;
	
	public static void main(String[] args) {
		try {
			tweets = new FileOutputStream("Tweets.txt");
			usuarios = new BufferedReader(new FileReader("Usuarios.txt"));
			String usuario;
			while ((usuario = usuarios.readLine()) != null) {
				getTweets(usuario);
			}
			usuarios.close();
			tweets.close();
		} catch (Exception ex) {
			System.out.println("Erro! " + ex.getMessage());
		}
	}
	
	private static void getTweets(String usuario) {
		try {
			HttpURLConnection urlConnection = (HttpURLConnection) (new URL("http://www.twitter.com/" + usuario)).openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String linha;
			while ((linha = in.readLine()) != null) {
				if (linha.contains("js-tweet-text")) {
					tweets.write(("Tweet: " + linha.subSequence(44, linha.length()) + " - Time: ").getBytes());
				} else if (linha.contains("data-time=")) {
					String time = linha.split("data-time=")[1].substring(1, 31);
					tweets.write((time + System.getProperty("line.separator")).getBytes());
				}
			}
			in.close();
			urlConnection.disconnect();
		} catch (Exception ex) {
			System.out.println("Erro! " + ex.getMessage());
		}
	}
}